package com.pi.pro.xcmg.am.was.web.cust.controller;


import com.pi.common.CodesConstants;
import com.pi.common.utils.TextUtils;
import com.pi.framework.core.controller.BaseCrudController;
import com.pi.framework.core.model.IEditable;
import com.pi.framework.core.model.IEnabled;
import com.pi.framework.core.model.IdTreeEntity;
import com.pi.framework.core.service.ICrudService;
import com.pi.framework.core.util.ConvertUtils;
import com.pi.framework.core.util.SecurityUtils;
import com.pi.framework.core.util.StringUtils;
import com.pi.framework.core.validator.DataValidator;
import com.pi.framework.util.JxlsReader;
import com.pi.pro.xcmg.am.common.XcmgAmConstants;
import com.pi.pro.xcmg.am.common.vo.act.CountItemDto;
import com.pi.pro.xcmg.am.was.fac.service.WasCustomWorkService;
import com.pi.wms.common.WmsConstants;
import com.pi.wms.dto.act.TaskActionDto;
import com.pi.wms.dto.base.LocationLineDto;
import com.pi.wms.entity.TwaDocCoDetails;
import com.pi.wms.entity.TwaDocCoHeader;
import com.pi.wms.entity.TwaDocWaveHeader;
import com.pi.wms.entity.TwtActTaskList;
import com.pi.wms.fac.LocationResolver;
import com.pi.wms.service.CoDetailsService;
import com.pi.wms.service.CoService;
import com.pi.wms.service.StorageService;
import com.pi.wms.service.TaskService;
import com.pi.wms.vo.master.MaterialVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.jpa.datatables.mapping.DataTablesInput;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;


@Slf4j
@Controller
@RequestMapping("/inventory/co/ca")
public class CustApplyCoController extends BaseCrudController<TwaDocCoHeader, Long> {

	@Autowired
	private CoService service;

	@Autowired
	private CoDetailsService detailsService;

	@Autowired
	private StorageService storageService;

	@Autowired
	private TaskService taskService;

	@Autowired
	private WasCustomWorkService wasCustomWorkService;

    @Autowired
    private LocationResolver locationResolver;

	@Override
	protected String getPrefix() {
		return "co";
	}


	@Override
	protected String getRequestMapping() {
		return "/inventory/co";
	}
	
	@Override
	protected ICrudService<TwaDocCoHeader, Long> getCrudService() {
	    return service;
	}

	@Autowired
	private DataValidator validator;


	@Override
    protected void preSave(TwaDocCoHeader m, HttpServletRequest request) {
	    super.preSave(m, request);
	    if (StringUtils.isNullOrBlank(m.getType())){
	        m.setType(WmsConstants.CO_TYPE_NORMAL);
        }
    }

	@PostMapping("gendetails")
	public String generateDetails(@RequestParam("ids") Long[] ids, Model model, HttpServletRequest request,
								  RedirectAttributes redirectAttributes) {
		model.addAttribute("params", getParams(request));
		String msg="";
		boolean failed=false;
		String worker=SecurityUtils.getLoginUsername();
		if (ids != null && ids.length > 0) {
			for (Long id : ids) {
				try{
					msg = this.wasCustomWorkService.checkout(id, worker);
					if (!StringUtils.isNullOrBlank(msg)){
						addErrorMessage(redirectAttributes, "生成单证行失败:"+msg);
						return super.redirect("");
					}
				}catch(Exception e){
					failed=true;
					log.error("生成单证行失败", e);
					addErrorMessage(redirectAttributes, "生成单证行失败");
				}
			}
			if (!failed){
				addSuccessMessage(redirectAttributes, "生成单证行成功");
			}
		}
		return super.redirect("");
	}

	@PostMapping("workstation")
	public String workStation(@RequestParam("ids") Long[] ids, @RequestParam("workstations") List<String> workstations,
                              Model model, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		//
		model.addAttribute("params", getParams(request));
		String m = "";
		TwaDocCoHeader header = null;
		List<TwtActTaskList> tasks = null;

		if ((ids == null) || (ids.length == 0)) {
			addSuccessMessage(redirectAttributes, "设置拣货站台成功");
			return this.redirect("");
		}
		int ccount=0;
		for (Long id : ids) {
			if (id == null) {
				continue;
			}
			ccount=this.wasCustomWorkService.coDetailsContainerCount(id);
			if (ccount>XcmgAmConstants.COUNT_MAX_COTAINER_COUNT){
				addErrorMessage(redirectAttributes, "盘点单明细行太多，可能造成设备系统繁忙。请重新创建作业范围更小的盘点单。");
				return this.redirect("");
			}
			m = this.wasCustomWorkService.setCountStation(id, workstations, SecurityUtils.getLoginUsername());
			if (!StringUtils.isNullOrBlank(m)) {
				addErrorMessage(redirectAttributes, m);
				return this.redirect("");
			}
		}
		addSuccessMessage(redirectAttributes, "设置盘点站台成功");
		return this.redirect("");
	}


	@PostMapping("gentask")
	public String generateTask(@RequestParam("ids") Long[] ids, Model model, HttpServletRequest request,
							   RedirectAttributes redirectAttributes) {
		model.addAttribute("params", getParams(request));
		String msg="";
		boolean failed=false;
		String worker=SecurityUtils.getLoginUsername();
		TaskActionDto actionDto=new TaskActionDto();
		actionDto.setWorker(worker);
		actionDto.setWorkTime(new Date());
		List<TwtActTaskList> taskall=new ArrayList<>();
		List<TwtActTaskList> tasks=new ArrayList<>();
		List<TwtActTaskList> wcstasks=new ArrayList<>();
		String batchnum=null;
        LocationLineDto loc=null;
		TwaDocCoHeader header=null;
		Map<Long, TwaDocCoHeader> headers=new HashMap<>();
		if (ids != null && ids.length > 0) {
			for (Long id : ids) {
				try{
				    header=this.service.findById(id);
				    if (header==null){
                        addErrorMessage(redirectAttributes, "找不到盘点单,请确认是否已删除.盘点单ID:"+String.valueOf(id));
                        return this.redirect("");
                    }
				    if (StringUtils.isNullOrBlank(header.getDockNumber())){
                        addErrorMessage(redirectAttributes, "请先指定盘点站台.单号:"+header.getDocumentNumber());
                        return this.redirect("");
                    }
                    if (!WmsConstants.CO_STATUS_CREATE.equalsIgnoreCase(header.getStatus())){
                        addErrorMessage(redirectAttributes, "盘点单已经开始作业,不能重复执行.单号:"+header.getDocumentNumber());
                        return this.redirect("");
                    }
					actionDto.setBatchNumber(TextUtils.genBatchNumber());
					msg = this.storageService.checkoutTask(id, actionDto);
					if (!StringUtils.isNullOrBlank(msg)){
						addErrorMessage(redirectAttributes, "生成盘点任务失败:"+msg);
						return this.redirect("");
					}
					tasks=this.taskService.queryWorkingTasks(WmsConstants.TASK_TYPE_COUNT, id);
					if ((tasks!=null)||(tasks.size()>0)){
					    for (TwtActTaskList t:tasks){
					        if (t==null){
					            continue;
                            }
                            header=headers.get(t.getDocId());
					        if (header==null){
					            header=this.service.findById(t.getDocId());
					            if (header==null){
					                continue;
                                }
                                headers.put(header.getId(), header);
                            }
                            if (!StringUtils.isNullOrBlank(header.getCategory())){
                                t.setCategory(header.getCategory());
                            }
                            if (!StringUtils.isNullOrBlank(header.getCreateSource())){
                                t.setTaskSchema(header.getCreateSource());
                            }
                            if (!StringUtils.isNullOrBlank(header.getPlanLoadPlace())){
                                t.setTaskFeature(header.getPlanLoadPlace().trim());
                            }
                            /**
                            if (!StringUtils.isNullOrBlank(details.getDEdi13())){
                                t.setUdf09(details.getDEdi13().trim());
                            }
                             **/
                            if (!StringUtils.isNullOrBlank(header.getDockNumber())){
                                loc=this.locationResolver.lookup(header.getDivisionId(), header.getDockNumber().trim());
                                if (loc!=null){
                                    t.setToLocId(loc.getLocationId());
                                    t.setToLocSeq(loc.getPkSeqCode());
                                    t.setPlantoLocId(t.getToLocId());
                                    t.setPlantoLocSeq(t.getToLocSeq());
                                    this.taskService.save(t);
                                }
                            }
                        }
					    taskall.addAll(tasks);
                    }
				}catch(Exception e){
					failed=true;
					log.error("生成盘点任务失败", e);
					addErrorMessage(redirectAttributes, "生成盘点任务失败");
				}
			}
			if ((taskall!=null) && (taskall.size()>0)){
                batchnum=TextUtils.genBatchNumber();
                for (TwtActTaskList t:taskall){
                    if (t==null){
                        continue;
                    }
                    loc=this.locationResolver.lookup(t.getFromLocId());
                    if (loc==null){
                        continue;
                    }
                    if (!WmsConstants.LOCATION_TYPE_BIN.equalsIgnoreCase(loc.getLocationType())){
                        continue;
                    }
                    wcstasks.add(t);
                }
                msg = this.wasCustomWorkService.sendWasTaskToWcs(wcstasks, batchnum, SecurityUtils.getLoginUsername());
                if (!StringUtils.isNullOrBlank(msg)){
                    failed=true;
                    addSuccessMessage(redirectAttributes, "生成盘点任务出错:"+msg);
                }
            }
			if (!failed){
				addSuccessMessage(redirectAttributes, "生成盘点任务成功");
			}
		}
		return super.redirect("");
	}

    @PostMapping("deliver")
    public String deliver(@RequestParam("ids") Long[] ids, Model model, HttpServletRequest request, RedirectAttributes redirectAttributes) {
        model.addAttribute("params", getParams(request));
        String msg="";
        if ((ids==null)||(ids.length==0)){
            addSuccessMessage(redirectAttributes, "发布成功");
            return super.redirect("");
        }
        TaskActionDto actionDto=new TaskActionDto();
		actionDto.setWorker(SecurityUtils.getLoginUsername());
        for (Long id:ids){
            if (id==null){
                continue;
            }
            msg=this.wasCustomWorkService.deliverCount(id, actionDto);
            if (!StringUtils.isNullOrBlank(msg)){
                addErrorMessage(redirectAttributes, "发布盘点单失败:"+msg);
                return super.redirect("");
            }
            msg = this.taskService.closeDocumentTask(id, null, WmsConstants.TASK_TYPE_COUNT, actionDto);
            if (!StringUtils.isNullOrBlank(msg)){
                addErrorMessage(redirectAttributes, "发布盘点单失败:"+msg);
                return super.redirect("");
            }
            addSuccessMessage(redirectAttributes, "发布成功");
        }
        return super.redirect("");
    }


	@GetMapping(value = { "/import" })
	public String importIndex(Model model,  HttpServletRequest request, RedirectAttributes redirectAttributes) {
		return super.view(getPrefix() + "_import");
	}

	@PostMapping(value = { "/upload" })
	public String upload(@RequestParam MultipartFile file, Model model, String chkUpdate, HttpServletRequest request,
						 RedirectAttributes redirectAttributes) {
		if (file != null) {
			List<CountItemDto> countitemList = new ArrayList<CountItemDto>();
			Map<String, Object> beans = new HashMap<String, Object>();
			beans.put("countitemList", countitemList);
			try {
				List<String> errors = JxlsReader.readXls(
						new ClassPathResource("/templates/inventory/count.xml").getInputStream(), file.getInputStream(),
						beans);
				if (errors != null && !errors.isEmpty()) {
					addErrorMessage(redirectAttributes, (String[]) errors.toArray(new String[0]));
					return "redirect:" + getRequestMapping() + "/import";
				}

				String message = validator.validateMessage(countitemList);
				if (message != null) {
					addErrorMessage(redirectAttributes, "导入文件验证有错误! " + message);
					redirectAttributes.addFlashAttribute("hasError", true);
				}else {
					try {
						this.wasCustomWorkService.loadCountData(XcmgAmConstants.DIVISION_WH101_CODE, countitemList, SecurityUtils.getLoginUsername());
						redirectAttributes.addFlashAttribute("hasError", false);
						addSuccessMessage(redirectAttributes, "数据导入成功!");
					} catch (Exception e) {
						addErrorMessage(redirectAttributes, e.getMessage());
						redirectAttributes.addFlashAttribute("hasError", true);
					}
				}
				redirectAttributes.addFlashAttribute("countitemList", countitemList);
			} catch (IOException e) {
				e.printStackTrace();
				addErrorMessage(redirectAttributes, "读取文件异常:" + e.getLocalizedMessage());
			} catch (Exception e) {
				e.printStackTrace();
				addErrorMessage(redirectAttributes, "数据导入异常:" + e.getLocalizedMessage());
			}
		} else {
			addErrorMessage(redirectAttributes, "上传文件为空!");
		}
		return "redirect:" + getRequestMapping() + "/ca/import";
	}


	@Override
	protected String redirect(String relativeUrl) {
		if (!StringUtils.isNullOrBlank(relativeUrl) && !relativeUrl.startsWith("/")) {
			relativeUrl = "/" + relativeUrl;
		}
		return "redirect:" + this.referUrl() + relativeUrl;
	}

	private String referUrl() {
		return "/inventory/co/";
	}

}
